// pages/poem/poem.js
const datautils = require("../../utils/datautil.js")
const fs = wx.getFileSystemManager() // 文件管理器API
const wxAudio = wx.createInnerAudioContext({}) // 音频API
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    showPage: false,
    images: [],
    playNumber: 20,
    resultRight: 0,
    resultError: 0,
    currentAudio: {
      "icon": "",
      "chinese": "",
      "english": ""
    },
    clickCount: 0,
    errorCount: 0,
    success: datautils.getSuccessData(),
    error: datautils.getErrorData()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.transData()
  },
  /**
   * 页面显示时回调
   */
  onShow(){
    if(this.data.showPage){
      this.transData()
    }
    this.data.showPage=true
  },
  transData() {
    var originData = [];
    this.data.images = [];
    var originData = datautils.getData(0).concat(datautils.getData(1))
      .concat(datautils.getData(2)).concat(datautils.getData(4));
    this.data.playNumber = app.globalData.playLeave / 100 * originData.length;
    for (var i = 0; i < this.data.playNumber; i++) {
      var random = Math.floor(Math.random() * originData.length);
      this.data.images.push(originData[random]);
    }
    this.setData({
      images: this.data.images
    })


  },
  onClick(event) {
    var it = this;
    var item = event.currentTarget.dataset.item;
    if (this.data.currentAudio.chinese == "") {
      wx.showToast({
        title: '请先点击开始',
        icon: "error"
      })
      return
    }
    if (item.chinese == this.data.currentAudio.chinese) {
      this.setData({
        resultRight: this.data.resultRight + 1,
        errorCount: 0
      })
      //播放成功的语音
      var random = Math.floor(Math.random() * this.data.success.length);
      var successAudio = this.data.success[random];
      this.sendToAudio(successAudio.chinese);
      //播放下一次语音
      setTimeout(function () {
        it.start()
      }, 2000)
    } else {
      this.data.errorCount = this.data.errorCount + 1;
      //播放失败的语音
      var random = Math.floor(Math.random() * this.data.error.length);
      var errorAudio = this.data.error[random];
      this.sendToAudio(errorAudio.chinese);
      if (this.data.errorCount == 3) {
        this.setData({
          resultError: this.data.resultError + 1,
          errorCount: 0
        })
        //播放下一次语音
        setTimeout(function () {
          it.start()
        }, 3000)
      } else {
        //可三次错误机会
      }
    }
  },

  reset() {
    this.transData();
    this.setData({
      resultRight: 0,
      resultError: 0,
      currentAudio: 0,
      errorCount: 0
    })
    //播放语音
    this.start()
  },
  rePlay() {
    // start currentAudio
    this.sendToAudio(this.data.currentAudio.chinese + "," + this.data.currentAudio.english)
  },

  start() {
    var random = Math.floor(Math.random() * this.data.images.length);
    this.setData({
      currentAudio: this.data.images[random]
    })
    console.log(this.data.currentAudio)
    // startAudio
    this.sendToAudio(this.data.currentAudio.chinese + "," + this.data.currentAudio.english)
  },

  jumpSetting() {
    wx.navigateTo({
      url: '../setting/setting',
    })
  },

  //发送字符到XF
  sendToAudio(text) {
    const target = `${wx.env.USER_DATA_PATH}/${new Date().getTime()}.mp3`
    var url = 'https://yuanxiapi.cn/api/voice/?text=' + text+'&spd='+app.globalData.audioSpeed;
    wx.request({
      url: url,
      method: 'GET',
      responseType: 'arraybuffer',
      success(result) {
        console.log(result)
        if (result.statusCode == 200 || result.statusCode == 201) {
          if (result.data != null) {
            fs.writeFile({
              filePath: target,
              data: result.data,
              encoding: 'binary',
              success: (res) => {
                wxAudio.src = target
                console.log("success")
              },
              fail: () => {
                wx.showModal({
                  title: '播放失败,请重试',
                  content: result.errMsg,
                })
              }
            })
            // onCanplay监听音频进入可以播放状态的事件
            wxAudio.onCanplay(() => {
              wxAudio.play()
              console.log("onCanplay")
            })
          }
        }
      }
    })
  }
})